<template>
  <div class="upsert">
    <!--商品介绍--->
    <el-card class="box-card">
      <div class="clearfix">
        <h3>商品（Spu）介绍</h3>
      </div>
      <div class="text item textTop">
        <el-form
          ref="form"
          class="pop-up"
          status-icon
          :model="form"
          label-position="right"
          :rules="rules"
        >
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="title"
          >
            <el-input autocomplete="off" v-model="form.title"></el-input>
          </el-form-item>
          <el-form-item
            label="原始价格"
            prop="originalPriceRaw"
            :label-width="formLabelWidth"
          >
            <el-input
              autocomplete="off"
              v-model="form.originalPriceRaw"
              placeholder="0.00"
              ><el-button slot="append">元</el-button></el-input
            >
          </el-form-item>
          <el-form-item
            label="当前价格"
            prop="priceRaw"
            :label-width="formLabelWidth"
          >
            <el-input autocomplete="off" v-model="form.priceRaw"
              ><el-button slot="append">元</el-button></el-input
            >
          </el-form-item>
          <el-form-item
            label="VIP价格"
            prop="vipPriceRaw"
            :label-width="formLabelWidth"
          >
            <el-input
              autocomplete="off"
              v-model="form.vipPriceRaw"
              placeholder="0.00"
              ><el-button slot="append">元</el-button></el-input
            >
          </el-form-item>
          <el-form-item
            label="剩余库存"
            prop="continueNum"
            :label-width="formLabelWidth"
          >
            <el-input
              autocomplete="off"
              :disabled="disabled"
              v-model="form.stock"
            ></el-input>
          </el-form-item>
          <el-form-item label="运费模板" :label-width="formLabelWidth">
            <el-select
              v-model="form.freightTemplateId"
              placeholder="选择商品运费模板"
              clearable
            >
              <el-option
                v-for="item in batchCancel"
                :key="item.freightTemplateDO.id"
                :label="item.freightTemplateDO.templateName"
                :value="item.freightTemplateDO.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item
            label="是否在售"
            :label-width="formLabelWidth"
            prop="status"
          >
            <el-radio-group v-model="form.status">
              <el-radio v-model="form.status" :label="1">在售</el-radio>
              <el-radio v-model="form.status" :label="0">下架</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="商品图片" :label-width="formLabelWidth">
            <el-upload
              action="http://192.168.1.99:8080/upload/admin"
              list-type="picture-card"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              :on-remove="handleRemove"
              :file-list="imgList"
            >
              <i class="el-icon-plus"></i>
            </el-upload>
          </el-form-item>
          <el-form-item
            label="商品单位"
            prop="unit"
            :label-width="formLabelWidth"
          >
            <el-input
              autocomplete="off"
              v-model="form.unit"
              placeholder="件/个/盒"
            ></el-input>
          </el-form-item>
          <el-form-item label="所属类目" :label-width="formLabelWidth">
            <el-cascader
              placeholder="请选择"
              :options="spulist"
              ref="dom"
              :props="{ expandTrigger: 'hover' }"
              v-model="form.categoryId"
            ></el-cascader>
          </el-form-item>
          <el-form-item
            label="商品简介"
            prop="description"
            :label-width="formLabelWidth"
          >
            <el-input autocomplete="off" v-model="form.description"></el-input>
          </el-form-item>
          <el-form-item label="商品详细介绍" :label-width="formLabelWidth">
            <editor v-model="form.detail" :init="init"></editor>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
    <!--商品介绍结束-->
    <!--商品类型开始-->
    <el-card class="box-card">
      <div class="clearfix">
        <h3>商品类型(sku)</h3>
        <el-button type="primary" plain @click="typeAdd" class="addButton"
          >添加</el-button
        >
      </div>
      <div class="text item">
        <el-table
          :data="form.skuList"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column
            align="center"
            label="Sku条形码"
            prop="barCode"
          ></el-table-column>
          <el-table-column
            align="center"
            label="类型名"
            prop="title"
          ></el-table-column>
          <el-table-column align="center" label="原价"
            ><template slot-scope="scope">{{
              scope.row.originalPrice / 100
            }}</template></el-table-column
          >
          <el-table-column align="center" label="现价"
            ><template slot-scope="scope">{{
              scope.row.price / 100
            }}</template></el-table-column
          >
          <el-table-column align="center" label="VIP价格"
            ><template slot-scope="scope">{{
              scope.row.vipPrice / 100
            }}</template></el-table-column
          >
          <el-table-column
            align="center"
            label="库存"
            prop="stock"
          ></el-table-column>
          <el-table-column align="center" label="操作"
            ><template slot-scope="scope">
              <el-button
                class="button_remove"
                size="mini"
                type="danger"
                @click="priceCancel(scope.index)"
                >删除</el-button
              > </template
            ><el-button
              class="button_remove"
              size="mini"
              type="danger"
              @click="handleDelete(scope.row)"
              >删除</el-button
            ></el-table-column
          >
        </el-table>
      </div>
    </el-card>
    <!--商品类型结束-->
    <!--商品类型弹出框开始-->
    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form
        :model="goodsType"
        :rules="goodsTypes"
        ref="typeAdd"
        class="pop-up"
        status-icon
      >
        <el-form-item
          prop="barCode"
          label="类型条码"
          :label-width="formLabelWidth"
        >
          <el-input v-model="goodsType.barCode" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="title"
          label="类型名称"
          :label-width="formLabelWidth"
        >
          <el-input v-model="goodsType.title" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item
          prop="imgUrl"
          label="图片(可空)"
          :label-width="formLabelWidth"
        >
          <el-upload
            class="avatar-uploader"
            action="http://192.168.1.99:8080/upload/admin"
            :show-file-list="false"
            :on-success="handleAvatarGoodsType"
            :before-upload="beforeAvatarUpload"
          >
            <img v-if="goodsType.img" :src="goodsType.img" class="avatar" />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item
          placeholder="0.00"
          prop="originalPrice"
          label="原始价格"
          :label-width="formLabelWidth"
        >
          <el-input
            placeholder="0.00"
            v-model="goodsType.originalPrice"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="当前价格"
          :label-width="formLabelWidth"
          prop="price"
        >
          <el-input
            placeholder="0.00"
            v-model="goodsType.price"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          prop="vipPrice"
          label="VIP价格"
          :label-width="formLabelWidth"
        >
          <el-input
            placeholder="0.00"
            v-model="goodsType.vipPrice"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item prop="stock" label="库存" :label-width="formLabelWidth">
          <el-input v-model="goodsType.stock" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="typeAdds('typeAdd')">确 定</el-button>
      </div>
    </el-dialog>
    <!--商品类型弹出框结束-->

    <!--商品参数开始-->
    <el-card class="box-card">
      <div class="clearfix">
        <h3>商品类型(sku)</h3>
        <el-button type="primary" plain @click="parameterAdd" class="addButton"
          >添加</el-button
        >
      </div>
      <div class="text item">
        <el-table
          :data="form.attributeList"
          style="width: 100%"
          :default-sort="{ prop: 'date', order: 'descending' }"
        >
          <el-table-column
            align="center"
            label="商品参数名称"
            prop="attribute"
          ></el-table-column>
          <el-table-column
            align="center"
            label="商品参数值"
            prop="value"
          ></el-table-column>
          <el-table-column align="center" label="操作"
            ><template slot-scope="scope">
              <el-button
                class="button_remove"
                size="mini"
                type="danger"
                @click="argumentCancel(scope.index)"
                >删除</el-button
              >
            </template></el-table-column
          >
        </el-table>
      </div>
    </el-card>
    <!--商品参数结束-->
    <!--商品参数弹出框开始-->
    <el-dialog :title="title" :visible.sync="parameterFormVisible">
      <el-form
        :model="argumentform"
        ref="argumentform"
        :rules="argumentforms"
        class="pop-up"
        status-icon
      >
        <el-form-item
          label="商品参数名称"
          :label-width="formLabelWidth"
          prop="attribute"
        >
          <el-input
            v-model="argumentform.attribute"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item
          label="商品参数值"
          :label-width="formLabelWidth"
          prop="value"
        >
          <el-input v-model="argumentform.value" autocomplete="off"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="parameterFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="argumentAdd('argumentform')"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <!--商品参数弹出框结束-->
    <div class="bottom">
      <el-button @click="cancel">取 消</el-button>
      <el-button
        type="primary"
        @click="bool == '' ? adduser('form') : compile('form')"
        >{{ this.goodstitle }}</el-button
      >
    </div>
  </div>
</template>

<script>
import GoodsList from "@/api/goods/GoodsList";
//引入基本文件
import tinymce from "tinymce/tinymce";
import Editor from "@tinymce/tinymce-vue";
import "tinymce/themes/silver";

//引入你需要的插件
import "tinymce/plugins/image";
import "tinymce/plugins/link";
import "tinymce/plugins/code";
import "tinymce/icons/default";
import "tinymce/plugins/table";
import "tinymce/plugins/lists";
import "tinymce/plugins/contextmenu";
import "tinymce/plugins/wordcount";
import "tinymce/plugins/colorpicker";
import "tinymce/plugins/textcolor";
import "tinymce/skins/ui/oxide/skin.css";

export default {
  name: "tinymce",
  data() {
    return {
      init: {
        selector: "#textarea",
        skin_url: "/tinymce/skins/ui/oxide", // skin路径
        height: 300, //编辑器高度
        branding: true, //是否禁用“Powered by TinyMCE”
        menubar: true, //顶部菜单栏显示,
        plugins:
          "link lists image code table colorpicker textcolor wordcount contextmenu",
        toolbar:
          "bold italic underline strikethrough | fontsizeselect | forecolor backcolor | alignleft aligncenter alignright alignjustify | bullist numlist | outdent indent blockquote | undo redo | link unlink image code | removeformat",
        images_upload_handler: (blobInfo, success, failure) => {
          const img = "data:image/jpeg;base64," + blobInfo.base64();
          success(img);
          console.log(failure);
        }
      },

      formLabelWidth: "100px", //宽度
      title: "",
      goodstitle: "保存商品", //弹出框确定按钮
      bool: "", //布尔值 判断编辑还是修改 为true是创建 否则就是修改
      disabled: true, //是否禁用
      spulist: [], //spu数据接收数组
      dialogVisible: false, //图片
      dialogFormVisible: false, //商品类型弹出框
      parameterFormVisible: false, //商品参数弹出框
      formclone: "", //将表单初始化内容克隆 用于重置表单
      typeclone: "", //将类型表单初始化内容克隆 用于重置表单
      parameterclone: "", //将参数初始化内容克隆 用于重置表单
      batchCancel: [], //运费模板数据
      imgList: [],
      //表单
      form: {
        status: "", //是否在售
        imgList: [], //图片列表
        categoryId: "", //所属类目
        title: "", //商品名称
        originalPriceRaw: "添加商品", //原始价格
        priceRaw: "0", //当前价格
        vipPriceRaw: "", //VIP价格
        stock: "0", //剩余库存
        freightTemplateId: "", //运费模板
        unit: "", //单位
        img: "", //上传图片
        description: "",
        detail: "",
        skuList: [], //商品类目
        attributeList: [], //商品参数
        id: "" //商品id
      },
      //商品类型
      goodsType: {
        barCode: "", //类型条形码
        title: "", //类型标题
        stock: "", //剩余库存
        originalPrice: "", //原始价格
        price: "", //当前价格
        vipPrice: "", //VIP价格
        img: "" //图片
      },
      //商品参数
      argumentform: {
        attribute: "", //参数名
        value: "" //参数值
      },
      //商品介绍表单验证
      rules: {
        //商品名称
        title: [
          { message: "商品名称不能为空", trigger: "blur", required: true }
        ],
        //原始价格
        originalPriceRaw: [
          { message: "商品原价不能为空", trigger: "blur", required: true },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            trigger: "blur",
            message: "请输入正数"
          }
        ],
        //当前价格
        priceRaw: [
          { message: "商品现价不能为空", trigger: "blur", required: true },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            trigger: "blur",
            message: "请输入正数"
          }
        ],
        //VIP价格
        vipPriceRaw: [
          { message: "商品VIP价格不能为空", trigger: "blur", required: true },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            trigger: "blur",
            message: "请输入正数"
          }
        ],
        //是否在售
        status: [
          { message: "请选择商品状态", trigger: "change", required: true }
        ],
        //商品单位
        unit: [{ message: "商品单位不能为空", trigger: "blur", required: true }]
      },
      //商品类型表单验证
      goodsTypes: {
        barCode: [
          { message: "类型条码不能为空", trigger: "blur", required: true },
          { pattern: /^[0-9]*$/, trigger: "blur", message: "请输入整数" }
        ],
        title: [
          { message: "类型名称不能为空", trigger: "blur", required: true }
        ],
        stock: [
          { message: "类型库存不能为空", trigger: "blur", required: true },
          { pattern: /^[0-9]*$/, trigger: "blur", message: "请输入整数" }
        ],
        originalPrice: [
          { message: "类型原价不能为空", trigger: "blur", required: true },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            trigger: "blur",
            message: "请输入正数"
          }
        ],
        price: [
          { message: "类型现价不能为空", trigger: "blur", required: true },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            trigger: "blur",
            message: "请输入正数"
          }
        ],
        vipPrice: [
          { message: "类型VIP不能为空", trigger: "blur", required: true },
          {
            pattern: /^[+]{0,1}(\d+)$|^[+]{0,1}(\d+\.\d+)$/,
            trigger: "blur",
            message: "请输入正数"
          }
        ]
      },
      //商品参数表单验证
      argumentforms: {
        attribute: [
          { message: "属性名称不能为空", trigger: "blur", required: true }
        ],
        value: [{ message: "属性值不能为空", trigger: "blur", required: true }]
      }
    };
  },
  components: { Editor },
  mounted() {
    tinymce.init({});
  },
  created() {
    if (this.$route.query.id !== undefined) {
      //判断是添加还是编辑
      this.goodstitle = "更新商品";
      this.bool = this.$route.query.id; //将传过来的参数赋值用于判断
      GoodsList.look(this.bool).then(res => {
        //调用查看接口
        if (res.data.errmsg == "成功") {
          for (const key in res.data.data) {
            this.form[key] = res.data.data[key];
          }

          this.form.categoryId = res.data.data.categoryIds.reverse(); //将数值翻转
          this.imgList = res.data.data.imgList.map(item => ({ url: item }));
          this.form.originalPriceRaw = res.data.data.originalPrice / 100; //将原始价格除于100
          this.form.priceRaw = res.data.data.price / 100; //将当前价格除于100
          this.form.vipPriceRaw = res.data.data.vipPrice / 100; //将VIP价格除于100
        }
      });
    }
    //spu树接口调用
    GoodsList.spu().then(res => {
      this.spulist = res.data.data;
      this.getTreeData(this.spulist);
    });
    //获取到运费模板数据
    GoodsList.batch().then(res => {
      this.batchCancel = { ...res.data.data };
    });
    //将三个表单的初始值赋值 用于清空内容
    this.formclone = JSON.parse(JSON.stringify(this.form)); //将form初始状态再次赋值给form表单
    this.typeclone = JSON.parse(JSON.stringify(this.goodsType)); //将form初始状态再次赋值给form表单
    this.parameterclone = JSON.parse(JSON.stringify(this.argumentform)); //将参数初始状态再次赋值给参数表单
  },
  methods: {
    //添加数据接口
    adduser(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.form.imgList = this.imgList.map(item => item.url); //将图片赋值
          if (this.imgList.length === 0) {
            this.Prosperity.Messages("请上传至少一张图片", "error"); //判断图片数量
          } else {
            this.category(); //调用获取类目id方法
            var _this = this;
            GoodsList.adduser(_this.form)
              .then(res => {
                if (res.data.errmsg == "成功") {
                  this.$router.replace({
                    path: "goodsList"
                  });
                  _this.Prosperity.Messages("创建成功", "success");
                  _this.dialogFormVisible = false;
                } else {
                  _this.Prosperity.Messages(res.data.errmsg, "error");
                }
              })
              .catch(err => {
                return err;
              });
          }
        } else {
          this.Prosperity.Messages("请完善以上表单信息", "error");
          return false;
        }
      });
    },
    //编辑数据接口
    compile(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          this.form.imgList = this.imgList.map(item => item.url); //将图片赋值
          if (this.form.imgList.length === 0) {
            this.Prosperity.Messages("请上传至少一张图片", "error"); //判断图片数量
          } else {
            this.category(); //调用获取类目id方法
            var _this = this;
            GoodsList.compile(_this.form).then(res => {
              if (res.data.errmsg == "成功") {
                this.$router.replace({
                  path: "goodsList"
                });
                _this.Prosperity.Messages("编辑成功", "success");
                _this.dialogFormVisible = false;
              } else {
                _this.Prosperity.Messages(res.data.errmsg, "error");
              }
            });
          }
        } else {
          this.Prosperity.Messages("请完善以上表单信息", "error");
          return false;
        }
      });
    },
    //商品类型添加按钮
    typeAdd() {
      this.$nextTick(() => {
        //清除正则提示
        if (this.$refs.typeAdd) {
          this.$refs.typeAdd.resetFields();
        }
      });
      this.goodsType = JSON.parse(JSON.stringify(this.typeclone)); //将类型初始状态再次赋值给form表单
      this.title = "添加商品类型（Sku)";
      this.dialogFormVisible = true; //显示弹出框
    },
    //商品类型添加确定按钮
    typeAdds(typeAdd) {
      this.$refs[typeAdd].validate(valid => {
        if (valid) {
          this.goodsType.originalPrice = this.goodsType.originalPrice * 100;
          this.goodsType.price = this.goodsType.price * 100;
          this.goodsType.vipPrice = this.goodsType.vipPrice * 100;
          this.form.skuList.unshift(
            //添加
            JSON.parse(JSON.stringify(this.goodsType))
          );
          this.dialogFormVisible = false; //关闭弹出框
        } else {
          return false;
        }
      });
    },
    //删除商品类型
    priceCancel(index) {
      this.$confirm("此操作将永久删除该商品类型, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //确定删除的话
          this.form.skuList.splice(index, 1); //删除内容
          this.Prosperity.Messages("删除成功", "success");
        })
        .catch(() => {
          this.Prosperity.Messages("已取消删除");
        });
    },
    //商品参数添加按钮
    parameterAdd() {
      this.$nextTick(() => {
        //清除正则提示
        if (this.$refs.argumentform) {
          this.$refs.argumentform.resetFields();
        }
      });
      this.argumentform = JSON.parse(JSON.stringify(this.parameterclone)); //将参数初始状态再次赋值给参数表单
      this.title = "设置商品参数";
      this.parameterFormVisible = true; //显示弹出框
    },
    //商品参数确定按钮
    argumentAdd(argumentform) {
      this.$refs[argumentform].validate(valid => {
        if (valid) {
          this.form.attributeList.unshift(
            JSON.parse(JSON.stringify(this.argumentform))
          );
          this.parameterFormVisible = false; //关闭弹出框
        } else {
          return false;
        }
      });
    },
    //商品参数删除按钮
    argumentCancel(index) {
      this.$confirm("此操作将永久删除该商品参数, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          //确定删除的话
          this.form.attributeList.splice(index, 1); //删除内容
          this.Prosperity.Messages("删除成功", "success");
        })
        .catch(() => {
          this.Prosperity.Messages("已取消删除");
        });
    },
    //获取类目id
    category() {
      if (this.form.categoryId.length > 0) {
        this.form.categoryId = this.form.categoryId.pop();
      }
    },
    //取消按钮 跳回上一页
    cancel() {
      this.$router.replace({
        path: "goodslist"
      });
    },
    //递归
    getTreeData(data) {
      for (let item in data.length) {
        if (data[item].children.length < 1) {
          data[item].children = undefined;
        } else {
          this.getTreeData(data[item].children);
        }
      }
    },
    //图片
    handleRemove(file, fileList) {
      //图片删除
      this.imgList = fileList;
    },
    handleAvatarSuccess(res) {
      this.form.img = res.url;
      this.imgList.push({ url: res.url });
      console.log(this.imgList);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarGoodsType(res) {
      this.goodsType.img = res.url;
    }
  }
};
</script>

<style scoped>
/*卡片*/
.upsert {
  padding: 20px;
}
.button_remove {
  background: #f56c6c !important;
  color: #fff !important;
  border: #f56c6c 1px solid;
}
.textTop {
  padding-left: 75px !important;
}
.el-card {
  margin-bottom: 10px;
}
/*卡片结束*/

/*头像*/
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 143px;
  height: 143px;
  line-height: 143px;
  text-align: center;
  border: 1px dashed #d9d9d9;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
/*底部按钮*/
.addButton {
  margin-bottom: 15px;
}
.bottom {
  margin: 10px 0px;
  margin-bottom: 50px;
}
</style>
